package com.apes.fn.server.servicePlan.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.model.Filter;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.finance.model.CrossDept;
import com.apes.scm.masterdata.finance.model.CrossICServe;
import com.apes.scm.masterdata.finance.repository.CrossDefICRepository;
import com.apes.scm.masterdata.finance.repository.CrossDeptRepository;
import com.apes.scm.masterdata.finance.repository.CrossICRepository;
import com.apes.scm.masterdata.finance.repository.CrossICServeRepository;
import com.apes.scm.masterdata.finance.service.CrossICService;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Creator: zouyc
 * CreateDate: 2021-03-08 14:47
 * Description:
 **/
@Service("crossPlanService")
public class CrossPlanService extends DomainService {
    @Autowired
    PostRepository postRepository;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    CrossICRepository crossICRepository;
    @Autowired
    CrossDefICRepository crossDefICRepository;
    @Autowired
    CrossICServeRepository crossICServeRepository;

    private static String jeKunCompanyId = "1001"; //1001公司对应的编码

    /**
     * 获取服务相关的，当前角色的公司
     * @param re
     * @param <T>
     * @return
     */
    public <T>T currentPostCompany(SimpleRequest re){
        Object obj = postRepository.findOne(re.getPostId()).getCompany();
        if(obj == null) throw new RuntimeException("当前登录者在该部门POST，未配置公司");
        return (T) obj;
    }

    /**
     * 获取1001公司
     * @param
     * @param <T>
     * @return
     */
    public <T>T getCompanyForJeKun(){
        Object obj = partyRoleRepository.findOne(jeKunCompanyId);
        if(obj == null) throw new RuntimeException("当前登录者在该部门POST，未配置公司");
        return (T) obj;
    }

    /**
     * 增加两个fillter
     * @param req
     * @return
     */
    private JSONArray obtabinCrossCompany(SimpleRequest req){
        JSONArray list = new JSONArray();
        list.add(JSON.parse(JSON.toJSONString(new Filter("crossDefiIC.company.id",((PartyRole)getCompanyForJeKun()).getId(),"EQ",""))));
        list.add(JSON.parse(JSON.toJSONString(new Filter("crossDefiIC.company.id",((PartyRole)currentPostCompany(req)).getId(),"EQ",""))));
        return list;
    }

    private <T>T getPopBefore(JSONObject jo){
        //该查询需要添加两个属性（两个公司）
        return this.invoke("mas.crossICServe.findAll",jo);
    }

    private <T>T getAfterPop(JSONObject jo, SimpleRequest req) {
        List<Filter> condition1Array = new ArrayList();
        List<Filter> condition2Array = new ArrayList();
        JSONArray conditon = jo.getJSONArray("condition");
        conditon.forEach(itemJson ->{
            JSONObject item = (JSONObject)itemJson;
            if("crossICP".equals(item.getString("field"))){
                condition1Array.add(new Filter("crossDefiIC.id",item.getString("value"),item.getString("operator"),""));
            }else if("crossIC".equals(item.getString("field"))){
                condition1Array.add(new Filter("id",item.getString("value"),item.getString("operator"),""));
            }else if("matchFlag".equals(item.getString("field"))){
                boolean flag = false;
                try {
                    flag = item.getBoolean("value");
                }catch (Exception e){
                    flag = false;
                }
                JSONObject product = jo.getJSONObject("conditionModel").getJSONObject("node").getJSONObject("product");
                JSONObject classfy = product == null ? null : product.getJSONObject("classify");
                if(flag){ //匹配
                    if(product != null) condition2Array.add(new Filter("product.id",product.getString("id"),"EQ",""));
                    if(classfy != null) condition2Array.add(new Filter("classify.id",classfy.getString("id"),"EQ",""));
                }
            }
        });
        Group grouR = new Group();
        grouR.setFilters(condition1Array);
        grouR.setOperator("and");
        Group groupInner = new Group();
        groupInner.setFilters(condition2Array);
        groupInner.setOperator("or");

        Group groupCompany = new Group();
        List<Filter> companyFilter = new ArrayList<>();
        companyFilter.add(new Filter("crossDefiIC.company.id",((PartyRole)getCompanyForJeKun()).getId(),"EQ",""));
        companyFilter.add(new Filter("crossDefiIC.company.id",((PartyRole)currentPostCompany(req)).getId(),"EQ",""));
        groupCompany.setFilters(companyFilter);
        groupCompany.setOperator("or");

        List<Group> list = new ArrayList<>();
        if(condition2Array.size() != 0) list.add(groupInner);
        list.add(groupCompany);
        if(list.size() != 0) grouR.setGroups(list);
        Sort sort = new Sort(Sort.Direction.DESC, "crossDefiIC.id");
        List<CrossICServe> crossICServes = crossICServeRepository.findAll(grouR.build(true),sort);
        String deptId = getSession(req).getBranchId();
        if (deptId!=null){
            List<CrossDept> crossDepts = SpringManager.getBean(CrossDeptRepository.class).findAllByDept(SpringManager.getBean(DeptRepository.class).findOne(deptId));
            crossICServes = crossICServes.stream().filter(crossICServe -> {
                CrossDept orElse = crossDepts.stream().filter(crossDept -> crossDept.getCrossDefiIC().getId().equals(crossICServe.getCrossDefiIC().getId())).findFirst().orElse(null);
                return orElse == null;
            }).filter(crossICServe -> crossICServe.isValid()).collect(Collectors.toList());
        }
        return (T) SpringManager.getBean(CrossICService.class).pageInfo(jo,crossICServes,sort);
    }

    public  <T>T findForSelect(SimpleRequest req){
        JSONObject jo = req.getJO();
        if(jo.get("conditionModel") == null){ //非弹窗逻辑
            JSONObject group = jo.getJSONObject("group");
            if(group == null) throw new RuntimeException("查询条件缺失");
            //需要在
            JSONObject groupInner = new JSONObject();
            groupInner.put("groups",new JSONArray());
            groupInner.put("filters",obtabinCrossCompany(req));
            groupInner.put("operator","or");
            JSONArray groups = group.getJSONArray("groups");
            groups.add(groupInner);
            return getPopBefore(jo);
        } else{
            return getAfterPop(jo,req);
        }
    }

}
